<script setup lang="ts">
  import {
    postLoginAPI,
    postLoginWxMinAPI,
    iscaptcha,
    sendcode,
    registermobile,
    mobilelogin,
  } from '@/services/login'
  import { useMemberStore } from '@/stores'
  import { onLoad } from '@dcloudio/uni-app'
  import { defineAsyncComponent, reactive, ref } from 'vue'

  const MyCaptchaDialog = defineAsyncComponent(() => import('@/components/my-captcha/dialog.vue'))
  const myCaptchaDialogRef = ref()
  const CaptchaDialogRef = ref()
  const islogin = ref(true)
  const getCodeText = ref('获取验证码')
  const getCodeisWaiting = ref(false)

  //验证通过
  const onOk = async (data : any) => {
    if (codelogin.value) {
      setTimeout(async () => {
        popup.value?.close()
        getCodeText.value = '发送中...' //发送验证码
        getCodeisWaiting.value = true
        form.value = { ...form.value, captchaId: data.captchaId, track: data.track }
        const res = await sendcode(form.value)
        if (res.success) {
          form.value.codeId = res.data
          uni.showToast({
            title: '验证码已发送',
            icon: 'none',
          }) //弹出提示框
          setTimer() //调用定时器方法
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'error',
          })
        }
      }, 1000)
    } else {
      setTimeout(async () => {
        form.value.captchaId = data.captchaId
        form.value.captchaData = JSON.stringify(data.track)
        popup.value?.close()
        const res = await postLoginAPI(form.value)
        if (res.success) {
          loginSuccess(res.data)
        } else {
          uni.showToast({ icon: 'error', title: res.msg })
        }
      }, 1000)
    }
  }
  const onregister = async (data : any) => {
    setTimeout(async () => {
      register.value?.close()
      getCodeText.value = '发送中...' //发送验证码
      getCodeisWaiting.value = true

      formsms.value = { ...formsms.value, captchaId: data.captchaId, track: data.track }
      const res = await sendcode(formsms.value)
      if (res.success) {
        formsms.value.codeId = res.data
        uni.showToast({
          title: '验证码已发送',
          icon: 'none',
        }) //弹出提示框
        setTimer() //调用定时器方法
      } else {
        uni.showToast({
          title: res.msg,
          icon: 'error',
        })
      }
      //示例用定时器模拟请求效果
      //setTimeout(()用于在指定的毫秒数后调用函数或计算表达式
    }, 1000)
  }

  const register = ref()
  const getCodelogin = () => {
    if (getCodeisWaiting.value) {
      return
    }
    if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(form.value.mobile)) {
      //校验手机号码是否有误
      uni.showToast({
        title: '请填写正确手机号码',
        icon: 'none',
      })
      return false
    }
    popup.value?.open()
    //刷新滑块拼图
    myCaptchaDialogRef.value?.refresh()
  }
  const getCode = () => {
    if (getCodeisWaiting.value) {
      return
    }
    if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(formsms.value.mobile)) {
      //校验手机号码是否有误
      uni.showToast({
        title: '请填写正确手机号码',
        icon: 'none',
      })
      return false
    }
    register.value?.open()
    //刷新滑块拼图
    CaptchaDialogRef.value?.refresh()
  }

  const setTimer = () => {
    let holdTime = 60 //定义变量并赋值
    getCodeText.value = '重新获取(60)'
    //setInterval（）是一个实现定时调用的函数，可按照指定的周期（以毫秒计）来调用函数或计算表达式。
    //setInterval方法会不停地调用函数，直到 clearInterval被调用或窗口被关闭。
    let timer = setInterval(() => {
      if (holdTime <= 0) {
        getCodeisWaiting.value = false
        getCodeText.value = '获取验证码'
        clearInterval(timer) //清除该函数
        return //返回前面
      }
      getCodeText.value = '重新获取(' + holdTime + ')'
      holdTime--
    }, 1000)
  }
  // #ifdef MP-WEIXIN
  // 获取 code 登录凭证
  let code = ''
  onLoad(async () => {
    const res = await wx.login()
    code = res.code
  })

  // 获取用户手机号码
  const onGetphonenumber : UniHelper.ButtonOnGetphonenumber = async (ev) => {
    await checkedAgreePrivacy()
    const { encryptedData, iv } = ev.detail
    const res = await postLoginWxMinAPI({ code, encryptedData, iv })
    loginSuccess(res.result)
  }
  // #endif

  const codelogin = ref(false)
  const onGetphonenumberSimple = async () => {
    islogin.value = true
    codelogin.value = true
  }
  const oncodelogin = async () => {
    islogin.value = true
    codelogin.value = false
  }
  const loginSuccess = (profile : any) => {
    const currentPage = getCurrentPages().pop()
    const options = currentPage?.$page.options
    const redirect = options.redirect ? decodeURIComponent(options.redirect) : '';
    const params = options.params ? JSON.parse(decodeURIComponent(options.params)) : {};
    // 保存会员信息
    const memberStore = useMemberStore()
    memberStore.setProfile(profile)
    // 成功提示
    uni.showToast({ icon: 'success', title: '登录成功' })
    setTimeout(() => {
      if (redirect) {
        // 将 params 对象转换为查询字符串
        const paramString = Object.entries(params)
          .map(([key, value]) => `${key}=${value}`)
          .join('&');

        // 拼接完整的跳转 URL
        const redirectUrl = `/${redirect}?${paramString}`;
        if(redirect.includes('pages/my/my')){
          uni.switchTab({
            url: redirectUrl
          });
        }else{
          // 跳转到目标页面
          uni.redirectTo({
            url: redirectUrl
          });
        }

      } else {
        uni.switchTab({ url: '/pages/index/index' })
      }
    }, 1000)
  }

  // #ifdef H5
  const form = ref({
    mobile: '',
    password: '',
    captchaId: '',
    captchaData: '',
    code: '',
    track: '',
    codeId: '',
  })
  const formsms = ref({
    mobile: '',
    codeId: '',
    code: '',
    captchaId: '',
    track: '',
    password: '',
  })
  const popup = ref()
  // 表单提交
  const onSubmit = async () => {
    if (!isAgreePrivacy.value) {
      uni.showToast({
        icon: 'none',
        title: '请先阅读并勾选协议',
      })
      // 震动提示
      isAgreePrivacyShakeY.value = true
      setTimeout(() => {
        isAgreePrivacyShakeY.value = false
      }, 500)
      return false
    } else if (!form.value.mobile) {
      uni.showToast({
        title: '请输入手机号码',
        icon: 'none',
      })
      return Promise.reject(new Error('请输入手机号码'))
    } else if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(form.value.mobile)) {
      //校验手机号码是否有误
      uni.showToast({
        title: '请填写正确手机号码',
        icon: 'none',
      })
      return false
    } else if (!form.value.password && !codelogin.value) {
      uni.showToast({
        title: '请输入密码',
        icon: 'none',
      })
      return false
    }
    if (!codelogin.value) {
      const res = await iscaptcha()
      if (res.success) {
        if (res.data) {
          //刷新滑块拼图
          myCaptchaDialogRef.value?.refresh()
          popup.value?.open()
        } else {
          const res = await postLoginAPI(form.value)
          loginSuccess(res.data)
        }
      }
    } else {
      const res = await mobilelogin(form.value)
      if (res.success) {
        loginSuccess(res.data)
      } else {
        uni.showToast({ icon: 'error', title: res.msg })
      }
    }
  }
  const onreg = async () => {
    if (!isAgreePrivacy.value) {
      uni.showToast({
        icon: 'none',
        title: '请先阅读并勾选协议',
      })
      // 震动提示
      isAgreePrivacyShakeY.value = true
      setTimeout(() => {
        isAgreePrivacyShakeY.value = false
      }, 500)
      return false
    } else if (!formsms.value.mobile) {
      //校验手机号码是否有误
      uni.showToast({
        title: '请输入手机号码',
        icon: 'none',
      })
      return false
    } else if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(formsms.value.mobile)) {
      //校验手机号码是否有误
      uni.showToast({
        title: '请填写正确手机号码',
        icon: 'none',
      })
      return false
    } else if (!formsms.value.code) {
      //校验手机号码是否有误
      uni.showToast({
        title: '请输入验证码',
        icon: 'none',
      })
      return false
    } else if (!formsms.value.password) {
      //校验手机号码是否有误
      uni.showToast({
        title: '请输入密码',
        icon: 'none',
      })
      return false
    }
    const res = await registermobile(formsms.value)
    if (res.success) {
      uni.showToast({
        title: '注册成功',
        icon: 'success',
      })
      formsms.value = {
        mobile: '',
        codeId: '',
        code: '',
        captchaId: '',
        track: '',
        password: '',
      }
      if(res.data.token){
        loginSuccess(res.data)
      }else{
        islogin.value = true
      }
    } else {
      uni.showToast({
        title: res.msg,
        icon: 'error',
      })
    }
  }
  // #endif

  // 请先阅读并勾选协议
  const isAgreePrivacy = ref(false)
  const isAgreePrivacyShakeY = ref(false)
  const checkedAgreePrivacy = async () => {
    if (!isAgreePrivacy.value) {
      uni.showToast({
        icon: 'none',
        title: '请先阅读并勾选协议',
      })
      // 震动提示
      isAgreePrivacyShakeY.value = true
      setTimeout(() => {
        isAgreePrivacyShakeY.value = false
      }, 500)
      // 返回错误
      return Promise.reject(new Error('请先阅读并勾选协议'))
    }
  }
  const resetpassword = () => {
    uni.navigateTo({
      url: '/pages/login/forget',
    })
  }
  const onOpenPrivacyContract = () => {
    // #ifdef MP-WEIXIN
    // 跳转至隐私协议页面
    wx.openPrivacyContract({})
    // #endif
  }
</script>

<template>
  <view class="viewport">
    <view class="logo">
      <img src="@/static/images/icon.png"/>
    </view>
    <view class="login">
      <!-- 网页端表单登录 -->
      <!-- #ifdef H5 -->
      <view class="" v-if="islogin">
        <view class="username">
          <view class="get-code" v-if="codelogin" @click.stop="getCodelogin()">{{
            getCodeText
          }}</view>
          <input v-model="form.mobile" class="input" type="text" placeholder="请输入手机号码" />
        </view>
        <input v-if="codelogin" v-model="form.code" class="input" type="text" placeholder="请输入验证码" />
        <input v-else v-model="form.password" class="input" type="text" password placeholder="请输入密码" />
        <button @tap="onSubmit" class="button phone">登录</button>
        <view class="" style="
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 26rpx;
            color: #1e9fff;
            margin-top: 20rpx;
          ">
          <text @tap="islogin = !islogin">注册</text>
          <text style="margin: 0 10rpx">|</text>
          <text @click="resetpassword">忘记密码</text>
        </view>
      </view>

      <view class="" v-else>
        <view class="username">
          <view class="get-code" @click.stop="getCode()">{{ getCodeText }}</view>
          <input v-model="formsms.mobile" class="input" type="text" placeholder="请输入手机号码" />
        </view>
        <input v-model="formsms.code" class="input" type="text" placeholder="请输入验证码" />
        <input v-model="formsms.password" class="input" type="text" password placeholder="请输入密码" />
        <button @tap="onreg" class="button phone">注册</button>
        <view class="" style="
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 26rpx;
            color: #1e9fff;
            margin-top: 20rpx;
          ">
          <text @tap="islogin = !islogin">已有账号，立即登录</text>
          <text style="margin: 0 10rpx">|</text>
          <text @click="resetpassword">忘记密码</text>
        </view>
      </view>
      <!-- #endif -->
      <!-- 小程序端授权登录 -->
      <!-- #ifdef MP-WEIXIN -->
      <view class="button-privacy-wrap">
        <button :hidden="isAgreePrivacy" class="button-opacity button phone" @tap="checkedAgreePrivacy">
          请先阅读并勾选协议
        </button>
        <button class="button phone" open-type="getPhoneNumber" @getphonenumber="onGetphonenumber">
          <text class="icon icon-phone"></text>
          手机号快捷登录
        </button>
      </view>
      <!-- #endif -->
      <view class="extra">
        <view class="caption">
          <text>其他登录方式</text>
        </view>
        <view class="options">
          <!-- 通用模拟登录 -->
          <button @tap="onGetphonenumberSimple" v-if="!codelogin">
            <text class="icon icon-phone">验证码登录</text>
          </button>
          <button @tap="oncodelogin" v-else>
            <text class="icon icon-phone">密码登录</text>
          </button>
        </view>
      </view>
      <view class="tips" :class="{ animate__shakeY: isAgreePrivacyShakeY }">
        <label class="label" @click="isAgreePrivacy = !isAgreePrivacy">
          <radio class="radio" color="#1e9fff" :checked="isAgreePrivacy" @click="isAgreePrivacy = !isAgreePrivacy" />
          <text>登录/注册即视为你同意</text>
        </label>
        <navigator class="link" hover-class="none" url="./protocal">《服务条款》</navigator>
        和
        <text class="link" @tap="onOpenPrivacyContract">《隐私协议》</text>
      </view>
    </view>
    <uni-popup ref="popup" type="dialog">
      <MyCaptchaDialog ref="myCaptchaDialogRef" @ok="onOk" />
    </uni-popup>
    <uni-popup ref="register" type="dialog">
      <MyCaptchaDialog ref="CaptchaDialogRef" @ok="onregister" />
    </uni-popup>
  </view>
</template>

<style lang="scss">
  page {
    height: 100%;
  }

  .username {
    position: relative;

    .get-code {
      position: absolute;
      height: 80rpx;
      font-size: 26rpx;
      color: #999;
      display: flex;
      align-items: center;
      justify-content: center;
      right: 0;
      padding: 0 40rpx;
      z-index: 3;

      &:after {
        //点击以后，左边出现白色的线
        content: ' ';
        width: 1upx; //宽度为1upx
        height: 50upx; //高度为50upx
        background-color: #fff; //背景颜色为白色
        position: absolute;
        z-index: 3;
        margin-right: 100%;
        left: 0;
        top: 20upx;
      }
    }
  }

  .viewport {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 20rpx 40rpx;
  }

  .logo {
    flex: 1;
    text-align: center;

    img {
      height: 200rpx;
      width: 200rpx;
      transform: scale(0.8);
      margin-top: 5vh;
    }
  }

  .login {
    display: flex;
    flex-direction: column;
    height: 65vh;
    padding: 40rpx 20rpx 20rpx;

    .input {
      width: 100%;
      height: 80rpx;
      font-size: 28rpx;
      border-radius: 72rpx;
      border: 1px solid #ddd;
      padding-left: 30rpx;
      margin-bottom: 20rpx;
    }

    .button {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 80rpx;
      font-size: 28rpx;
      border-radius: 72rpx;
      color: #fff;

      .icon {
        font-size: 40rpx;
        margin-right: 6rpx;
      }
    }

    .phone {
      background-color: #1e9fff;
    }

    .wechat {
      background-color: #06c05f;
    }

    .extra {
      flex: 1;
      padding: 60rpx 70rpx 0;

      .caption {
        width: 440rpx;
        line-height: 1;
        border-top: 1rpx solid #ddd;
        font-size: 26rpx;
        color: #999;
        position: relative;

        text {
          transform: translate(-40%);
          background-color: #fff;
          position: absolute;
          top: -12rpx;
          left: 50%;
        }
      }

      .options {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 70rpx;

        button {
          padding: 0;
          background-color: transparent;

          &::after {
            border: none;
          }
        }
      }

      .icon {
        font-size: 24rpx;
        color: #444;
        display: flex;
        flex-direction: column;
        align-items: center;

        &::before {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 80rpx;
          height: 80rpx;
          margin-bottom: 6rpx;
          font-size: 40rpx;
          border: 1rpx solid #444;
          border-radius: 50%;
        }
      }

      .icon-weixin::before {
        border-color: #06c05f;
        color: #06c05f;
      }
    }
  }

  @keyframes animate__shakeY {
    0% {
      transform: translate(0, 0);
    }

    50% {
      transform: translate(0, -5rpx);
    }

    100% {
      transform: translate(0, 0);
    }
  }

  .animate__shakeY {
    animation: animate__shakeY 0.2s ease-in-out 3;
  }

  .button-privacy-wrap {
    position: relative;

    .button-opacity {
      opacity: 0;
      position: absolute;
      z-index: 1;
    }
  }

  .tips {
    font-size: 22rpx;
    color: #999;
    text-align: center;

    .radio {
      transform: scale(0.6);
      margin-right: -4rpx;
      margin-top: -4rpx;
      vertical-align: middle;
    }

    .link {
      display: inline;
      color: #1e9fff;
    }
  }
</style>
